<?php 
class db{
	private $conn;

	private $insert_id;
	private $num_rows = 0;

	private $ready    = false;
	private $request  = false;
	private $results  = false;

	public $query;


	public $tables = array(
		'classes',
		'field',
		'field_config',
		'forms',
		'options',
		'saved'
		);

	public function __construct($dbhost, $dbuser, $dbpass, $dbname = null){
		$this->conn = mysql_connect($dbhost, $dbuser, $dbpass) or die( mysql_error() );
		
		if( $this->conn )
			$this->ready = true;

		if( !is_null($dbname) )
			$this->select($dbname);

		foreach($this->tables as $table){
			$this->$table = DBPREFIX . $table;
		}
	}
	
	public function get_results($query = null){
		if( !is_null($query) )
			$this->query($query);

		return $this->results;
	}

	public function get_val($query = null){
		if( !is_null($query) )
			$this->query( $query );

		reset($this->results);
		return current($this->results[0]);
	}

	public function get_var( $query = null, $x = 0, $y = 0 ) {
		if ( $query )
			$this->query( $query );

		// Extract var out of cached results based x,y vals
		if ( !empty( $this->results[$y] ) ) {
			$values = array_values( get_object_vars( $this->results[$y] ) );
		}

		// If there is a value return it else return null
		return ( isset( $values[$x] ) && $values[$x] !== '' ) ? $values[$x] : null;
	}

	public function insert($table, $data, $type='INSERT'){
		if( !in_array( strtoupper($type), array('REPLACE', 'INSERT') ) )
			return false;

		$fields = array_keys( $data );
		$values = array_values( $data );

		$sql = "{$type} INTO `$table` (`" . implode( '`,`', $fields ) . "`) VALUES ('" . implode( "','", $values ) . "')";
		return $this->query( $this->prepare($sql, $data) );
	}
	public function insert_id(){
		return $this->insert_id;
	}

	public function num_rows(){
		return $this->num_rows;
	}

	public function prepare( $query = null ) {
		if ( is_null( $query ) )
			return;

		$args = func_get_args();
		array_shift( $args );
		if ( isset( $args[0] ) && is_array($args[0]) )
			$args = $args[0];
		$query = str_replace( "'%s'", '%s', $query );
		$query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
		$query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
		array_walk( $args, array( &$this, 'escape_by_ref' ) );
		return @vsprintf( $query, $args );
	}

	public function query($query){
		if( !$this->ready() )
			return FALSE;

		if( function_exists( 'apply_filters' ) )
			$query = apply_filters( 'query', $query );

		$return_val = 0; // numero de valores devueltos

		$this->query   = $query;
		$this->request = @mysql_query($this->query, $this->conn);

		if( $this->last_error = mysql_error( $this->conn ) )
			return false;

		if( preg_match('/^\s*(create|alter|truncate|drop) /i', $query) ){
			$return_val = $this->request;
		} elseif ( preg_match('/^\s*(insert|delete|update|replace) /i', $query) ){
			$this->rows_affected = mysql_affected_rows( $this->conn );

			if ( preg_match('/^\s*(insert|replace) /i', $query) ) 
				$this->insert_id = mysql_insert_id($this->conn);
			
			$return_val = $this->rows_affected;
		} else {
			$i = 0;
			while( $i < @mysql_num_fields($this->request) ){
				$this->col_info[$i] = @mysql_fetch_field( $this->request );
				$i++;
			}

			$num_rows = 0;
			while ( $row = @mysql_fetch_object($this->request) ) {
				$this->results[$num_rows] = $row;
				$num_rows++;
			}

			@mysql_free_result( $this->request );

			$this->num_rows = $num_rows;
			$return_val     = $num_rows;
		}
		return $return_val;
	}

	public function ready(){
		return $this->ready;
	}

	public function replace($table, $data){
		return $this->insert($table, $data, 'REPLACE');
	}

	public function select($dbname, $conn=null ){
		if( $this->ready() ){
			if( is_null($conn) )
				$conn = $this->conn;

			return mysql_select_db($dbname, $this->conn) or die( mysql_error() );
		} else
			return false;
	}

	public function update($table, $data = array(), $where=array()){
		if ( ! is_array( $data ) || ! is_array( $where ) )
			return false;

		$bits = $wheres = array();

		foreach( (array) array_keys($data) as $field ){
			$form = '%s';
			$bits[] = "`$field` = {$form}";
		}
		
		foreach( (array) array_keys( $where ) as $field ) {
			$form = '%s';
			$wheres[] = "`$field` = {$form}";
		}

		$sql = "UPDATE `$table` SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres );
		return $this->query( $this->prepare( $sql, array_merge( array_values( $data ), array_values( $where ) ) ) );
	}

	private function escape_by_ref( &$string ) {
		$string = $this->_real_escape( $string );
	}
	private function _real_escape( $string ) {
		if ( $this->dbh && $this->real_escape )
			return mysql_real_escape_string( $string, $this->dbh );
		else
			return addslashes( $string );
	}
	
	

}
?>